import { ActionContext } from 'vuex'
import { IUserState } from './state'
import { getUserInfo, login } from '@/api/system/user'
import baUserApi from '@/api/bg_user'
import mobileUserApi from '@/api/mobile_user/index'
import config from '@/config'
import {
  ACCESS_TOKEN,
  CURRENT_USER,
  IS_LOCKSCREEN,
  MOBILE_TOKEN,
  MOBILE_USER,
  USER_UID,
  ADMIN_USER
} from '@/store/mutation-types'
import { Storage } from '@/utils/Storage'
import store from '@/store'
import { IStore } from '@/store/types'
import { message } from 'ant-design-vue'
import { isWx } from '@/utils/common'

export const actions = {
  // 登录
  async login({ commit }: ActionContext<IUserState, IStore>, userInfo) {
    try {
      const response = await baUserApi.yzmLogin(userInfo)
      console.log(
        '%c 🥚 response: ',
        'font-size:20px;background-color: #465975;color:#fff;',
        response
      )
      const { token = '', userphone = '' } = response || ''
      if (token) {
        Storage.set(ACCESS_TOKEN, token)
        Storage.set(ADMIN_USER, userphone)
        Storage.set(IS_LOCKSCREEN, false)
        commit('setAdminToken', token)
        commit('setAdminInfo', userphone)
        store.commit('lockscreen/setLock', false)
      } else {
        message.error(response.retMsg)
      }
      return Promise.resolve(response)
    } catch (e) {
      return Promise.reject(e)
    }
  },
  // 登录
  async wxInfo({ commit }: ActionContext<IUserState, IStore>, uInfo) {
    try {
      uInfo.shopId = '2f99b465-5cd2-4152-99b4-655cd241521b'
      // @ts-ignore

      const response = await mobileUserApi.userRight(uInfo)
      console.log(
        '%c 🍋 用户企微信息ures: ',
        'font-size:20px;background-color: #E41A6A;color:#fff;',
        response
      )
      if (response.empAlias) {
        commit('setIsMicroEnterpriseUsers', true)
        console.log('有导购：', response.empAlias)
        return Promise.resolve(true)
      } else {
        commit('setIsMicroEnterpriseUsers', false)
        return Promise.resolve(false)
      }
    } catch (e) {
      return Promise.reject(e)
    }
  },

  // 获取用户信息
  getUserInfo({ commit }: ActionContext<IUserState, IStore>) {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then((response) => {
          const result = response.result

          if (result.role && result.role.permissions.length > 0) {
            const role = result.role
            role.permissions = result.role.permissions
            role.permissions.map((per) => {
              if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
                const action = per.actionEntitySet.map((action) => {
                  return action.action
                })
                per.actionList = action
              }
            })
            role.permissionList = role.permissions.map((permission) => {
              return permission.permissionId
            })
            commit('setRoles', result.role)
            commit('setUserInfo', result)
          } else {
            reject(new Error('getInfo: roles must be a non-null array !'))
          }

          // commit('SET_NAME', { name: result.name, welcome: welcome() })
          commit('setAvatar', result.avatar)

          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 获取用户信息
  async getMicroEnterpriseUsers({ commit, dispatch }: ActionContext<IUserState, IStore>) {
    if (!isWx()) return
    const uid = Storage.get(USER_UID)
    if (uid) {
      return Promise.resolve(await dispatch('wxInfo', { unionId: uid }))
    }
    return new Promise((resolve, reject) => {
      //@ts-ignore
      CMCCWECHAT.Acquire.initAndGetLoginWechat(
        {
          //活动标识
          activityId: '1029110205YAVZ'
          // config.activityId
        },
        async (weChatKey, res) => {
          Storage.set(USER_UID, res.data.unionid)
          resolve(await dispatch('wxInfo', { unionId: uid }))
          // mobileUserApi
          //   .userRight({
          //     unionId: res.data.unionid,
          //     shopId: '2f99b465-5cd2-4152-99b4-655cd241521b'
          //   })
          //   .then((ures) => {
          //     if (ures.empAlias) {
          //       commit('setIsMicroEnterpriseUsers', true)
          //       resolve(true)
          //       console.log('有导购：', ures.empId)
          //     } else {
          //       commit('setIsMicroEnterpriseUsers', false)
          //       resolve(false)
          //     }
          //     console.log(
          //       '%c 🍋 用户企微信息ures: ',
          //       'font-size:20px;background-color: #E41A6A;color:#fff;',
          //       ures
          //     )
          //   })
        },
        (code, openid) => {
          console.log(
            '%c 🥠 openid: ',
            'font-size:20px;background-color: #FFDD4D;color:#fff;',
            openid
          )
          resolve(false)
          commit('setIsMicroEnterpriseUsers', false)
          console.log(
            '%c 🥟 获取unionid 失败: ',
            'font-size:20px;background-color: #93C0A4;color:#fff;',
            code
          )
        }
      )
    })
  },

  // 登出
  async logout({ commit }: ActionContext<IUserState, IStore>) {
    commit('setRoles', [])
    commit('setUserInfo', '')
    Storage.remove(ACCESS_TOKEN)
    Storage.remove(CURRENT_USER)
    commit('setMobileInfo', '')
    commit('setMobileToken', '')
    Storage.remove(MOBILE_TOKEN)
    Storage.remove(MOBILE_USER)
    return Promise.resolve('')
  }
}
